<?php
namespace Model;
use Kuyuan\WqCore\Model\Model;

/**
 * 用户卡券
 * Class MemberCouponModel
 * @package Model
 */
class MemberCouponModel extends Model
{
    protected $_fields = array(
        "id",
        "uniacid",
        "uid",
        "red_id",
        "coupon_id",
        "indate",
        "time",
        "status"
    );

    //----set----
    /**
     * 设置卡券创建时间
     */
    public function setTimeAttr()
    {
        return TIMESTAMP;
    }

    /**
     * 设置卡券有效期
     * @param $_value
     * @param $_data
     * @return int
     */
    public function setIndateAttr($_value,$_data)
    {
        $_time = 1;
        $_coupon = CouponModel::where("id",$_data["coupon_id"])
                    ->field(array("time_type","time"))
                    ->noGetAttr(false)
                    ->find();
        if($_coupon["time_type"] == 1) {
            // 永久有效
            $_time = 1;
        } else if($_coupon["time_type"] == 2) {
            // 过期时间，有效期至
            $_time = $_coupon["time"];
        } else {
            $_time = TIMESTAMP + 86400 * $_coupon["time"];
        }
        return $_time;
    }

    //---get--

    /**
     * 获取卡券信息
     * @param $_value
     * @param $_data
     * @return mixed
     */
    public function getCouponAttr($_value,$_data)
    {
        $_coupon = array();
        if(isset($_data["coupon_id"])) {
            $_coupon = CouponModel::where("id",$_data["coupon_id"])
                ->field(array("name","cover","type","type_value","detail","address"))
                ->noGetAttr("time_str,status")
                ->cache(!KUYUAN_DEBUG)
                ->find();
            // 是否过期
            $_coupon["past"] = false;
            if($_data["indate"] == 1) {
                $_coupon["time_str"] = "永久有效";
            } else {
                $_coupon["time_str"] = date("Y-m-d",$_data["indate"]);
                if($_data["indate"]+86400-1 < TIMESTAMP) {
                    $_coupon["past"] = true;
                }
            }
        }
        return $_coupon;
    }
}